#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
using System.Linq;

public class AssetBundleNameSetter : EditorWindow
{
    static string folderPath = "Assets/WResources";
   
    [MenuItem("Tools/ AssetBundle Names Set Window")]
    public static void ShowWindow()
    {
        GetWindow<AssetBundleNameSetter>("Set AssetBundle Names");
    }
    private List<string> subFolders = new List<string>();
    private Dictionary<string, bool> foldToggle = new Dictionary<string, bool>();

    Vector2 scroll = Vector2.zero;
    private void OnEnable()
    {
        if (string.IsNullOrEmpty(folderPath))EditorUtility.DisplayDialog("Error", "根目录不存在！", "OK");
        ScanFolders();
    }
    private void ScanFolders()
    {
        subFolders.Clear();
        foldToggle.Clear();

        if (!Directory.Exists(folderPath))
        {
            EditorUtility.DisplayDialog("Error", "根目录不存在！", "OK");
            return;
        }

        // 只取一级目录
        var dirs = Directory.GetDirectories(folderPath, "*", SearchOption.TopDirectoryOnly);
        subFolders = dirs.Select(d => d.Replace("\\", "/")).ToList();
    }

    private void OnGUI()
    {
        GUILayout.Label("Select Folder to Set AssetBundle Names", EditorStyles.boldLabel);
        //选择文件夹
        // EditorGUILayout.BeginHorizontal();
        // folderPath = EditorGUILayout.TextField("Folder Path", folderPath);
        // if (GUILayout.Button("Browse", GUILayout.Width(60)))
        // {
        //     string selectedPath = EditorUtility.OpenFolderPanel("Select Folder", Application.dataPath, "");
        //     if (!string.IsNullOrEmpty(selectedPath))
        //     {
        //         if (selectedPath.StartsWith(Application.dataPath))
        //         {
        //             folderPath = "Assets" + selectedPath.Substring(Application.dataPath.Length);
        //         }
        //         else
        //         {
        //             EditorUtility.DisplayDialog("Invalid Path", "Please select a folder inside the Assets directory.", "OK");
        //         }
        //     }
        // }
        // EditorGUILayout.EndHorizontal();
        //显示子文件夹Toggle
        if (subFolders.Count < 10)
        {
            scroll = GUILayout.BeginScrollView(scroll, GUILayout.Height(subFolders.Count * 20));
        }
        else
        {
            scroll = GUILayout.BeginScrollView(scroll, GUILayout.Height(200));
        }
        foreach (var f in subFolders)
        {
            bool cur = foldToggle.ContainsKey(f) ? foldToggle[f] : false;
            foldToggle[f] = EditorGUILayout.ToggleLeft(f, cur);
        }
        GUILayout.EndScrollView();
        GUILayout.Space(10);
        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        if (GUILayout.Button("Set AssetBundle Names"))
        {
            assetBundleNames = new HashSet<string>();
            foreach (var f in subFolders)
            {
                if (foldToggle.ContainsKey(f) && foldToggle[f])
                    SetAssetBundleNames(f, assetBundleNames);
            }
            foreach (string bundleName in assetBundleNames)
            {
                Debug.Log(bundleName);
            }
        }
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
    }
     HashSet<string> assetBundleNames = new HashSet<string>();
    
    //[MenuItem("Tools/WinterFramwork/AssetBundle Names Setter")]
    private static void SetAssetBundleNames(string subFolders, HashSet<string> assetBundleNames)//
    {
       

        //string folderPath = "Assets/WResources/";
        if (!Directory.Exists(subFolders))
        {
            Debug.LogError("Folder does not exist: " + subFolders);
            return;
        }
        else
        {
            Debug.Log("Setting AssetBundle names for assets in: " + subFolders);
        }

        string[] guids = AssetDatabase.FindAssets("", new[] { subFolders });

        foreach (string guid in guids)
        {
            string assetPath = AssetDatabase.GUIDToAssetPath(guid);
            if (string.IsNullOrEmpty(assetPath)) continue;

            Object obj = AssetDatabase.LoadMainAssetAtPath(assetPath);
            if (obj == null) continue;
            if (obj is DefaultAsset && AssetDatabase.IsValidFolder(assetPath))
                continue;


            AssetImporter importer = AssetImporter.GetAtPath(assetPath);
            if (importer == null) continue;


            string fileName = Path.GetFileNameWithoutExtension(assetPath);
            string dirName = Path.GetDirectoryName(assetPath);
            dirName = dirName.Replace("\\", "/");
            string subFN = dirName.Replace(folderPath, "");
            string[] subFNs = subFN.Split('/');
            string bundleName = subFNs[0];

            for (int i = 1; i < subFNs.Length; i++)
            {
                bundleName += "_" + subFNs[i];
            }

            if (bundleName.StartsWith("_")) bundleName = bundleName.Substring(1);

            // 可选：统一小写
            assetBundleNames.Add(bundleName.ToLower());
            importer.assetBundleName = bundleName; // 可选：统一小写

        }

        AssetDatabase.RemoveUnusedAssetBundleNames();
        AssetDatabase.SaveAssets(); 
        AssetDatabase.Refresh();

        //Debug.Log($"AssetBundle names set for assets in: {subFolders}");
    }
}
#endif